<template>
  <div>
    <el-card class="search-cord" style="margin-bottom: 18px">
      <div
        class="ser-body"
        style="
          display: flex;
          justify-content: center; /* 水平居中 */
          align-items: center; /* 垂直居中 */
        "
      >
        <div
          class="date-picker"
          style="display: flex; justify-content: center; align-items: center"
        >
          <span class="demonstration">时间范围：</span>
          <el-date-picker
            style="width: 240px"
            v-model="value1"
            type="daterange"
            range-separator="To"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :size="size"
          />
        </div>
        <div
          class="ser-input"
          style="
            margin-left: 10px;
            display: flex;
            align-items: center;
            width: 460px;
          "
        >
          <el-input placeholder="选择分类" style="display: inline" />
          <el-input
            placeholder="讲师名称"
            style="display: inline; margin-left: 3px"
          />
          <el-input
            placeholder="课程名称"
            style="display: inline; margin-left: 3px"
          />

          <span style="display: inline; margin-left: 2px">
            <el-button type="success" :icon="Search">搜索课程</el-button>
          </span>
        </div>
      </div>
    </el-card>
    <el-card class="box-card">
      <el-button color="#5a98de" icon="Plus" @click="addCourse"
        >添加课程</el-button
      >
      <el-button
        color="#dd514c"
        @click="deleteCourses(multipleSelection)"
        icon="Delete"
        >批量删除</el-button
      >

      <!-- 表格组件，展示数据 -->
      <el-table
        style="margin: 18px 0px"
        border
        :data="getCourseData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" min-width="5%" align="center" />
        <el-table-column
          type="index"
          label="序号"
          min-width="8%"
          align="center"
        ></el-table-column>
        <!-- table-column：默认展示数据用div -->
        <el-table-column label="名称" min-width="20%" align="center">
          <template #="{ row }">
            <h1>{{ row.title }}</h1>
          </template>
        </el-table-column>
        <el-table-column label="封面" min-width="25%" align="center">
          <template #="{ row }">
            <el-image style="width: 100%" :src="row.cover_url" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column label="讲师" min-width="13%" align="center">
          <template #="{ row }">
            <h1>{{ row.teacher }}</h1>
          </template>
        </el-table-column>
        <el-table-column label="简介" min-width="20%" align="center">
          <template #="{ row }">
            <h1>{{ row.brief }}</h1>
          </template>
        </el-table-column>
        <el-table-column label="价格" min-width="10%" align="center">
          <template #="{ row }">
            <h1>{{ row.price }}</h1>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="30%" align="center">
          <template #="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="
                $router.push({
                  name: 'courseEdit',
                  query: { courseId: row.id }
                })
              "
              >课程编辑</el-button
            >
            <el-button
              type="primary"
              color="#5a98de"
              icon="List"
              size="small"
              @click="
                $router.push({
                  name: 'courseContent',
                  params: { courseId: row.id }
                })
              "
              >课时安排</el-button
            >
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              @click="deleteCourse(row.id)"
            >
              删除课程
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件
   pagination
  v-model:current-page:设置分页器当前页码
  v-model:page-size:设置每一个展示数据条数
  page-sizes: 每页显示个数选择器的选项设置,
  background:设置分页器按钮的
  layout:可以设置分页器六个子组件布局调整

  -->
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7]"
        background
        layout="prev, pager, next,jumper,->,sizes,total"
        :total="total"
        @current-change="getCourses(pageNum)"
        @size-change="sizeChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {
  reqCourseList,
  deleteCourseById,
  deleteCoursesByIds
} from '@/api/course/index'
import { onMounted, markRaw, toRaw } from 'vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
//导入element相关组件
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Search } from '@element-plus/icons-vue'

//获取路由器对象
let $router = useRouter()

const size = ref<'default' | 'large' | 'small'>('default')

const value1 = ref('')

console.log(value1, '11')

//当前页码
let pageNum = ref<number>(1)
//每一页展示多少数据,默认5条数据
let pageSize = ref<number>(5)
//存储已课程的总数量
let total = ref<number>(0)
//存储课程数据
let getCourseData = ref<any>([])
//获取所有课程的接口封装为一个函数:在任何情况下向获取数据,调用此函数即可
const getCourses = async (pager = 1) => {
  pageNum.value = pager
  let result = await reqCourseList(pageNum.value, pageSize.value)
  //  console.log(result)
  if (result.code == 0) {
    //存储已有课程总数量
    total.value = result.data.total
    getCourseData.value = result.data.list
  } else {
    getCourseData.value = []
  }

  console.log(getCourseData)
}

//组件挂载完毕钩子---发一次请求,获取第一页、一页三个课程数据
onMounted(() => {
  getCourses()
})

//分页器当前页码发生变化的时候会触发
//这里我们绑定的点击回调直接用的是之前写好的发送请求的回调。可以看出，发送请求的回调函数是有默认的参数：
//1.注意：因为current-change方法时element-plus封装好的，它会给父组件传递并注入一个参数（点击的页码），
//所以相当于把这个参数传递给了getCourses()函数，因此能够跳转到正确的页码数
//这里可以直接调用  getCourses()也可以拿到数据
// const sizeChange = () => {
//   //当前每一页的数据量发生变化的时候，当前页码归1
//   getCourses()
//   //  console.log(pagesize)
// }

//当下拉菜单发生变化的时候触发此方法
//这个自定义事件,分页器组件会将下拉菜单选中数据返回
const sizeChange = () => {
  //当前每一页的数据量发生变化的时候，当前页码归1
  getCourses()
  //  console.log(pagesize)
}

//点击添加课程，跳转到课程发布页面
const addCourse = () => {
  $router.push('/courses/create')
}

let multipleSelection = ref<any[]>([])

const handleSelectionChange = (val: any[]) => {
  // multipleSelection.value = val
  // console.log(multipleSelection.value)
  multipleSelection.value = []

  val.forEach((item) => {
    multipleSelection.value.push(item.id)
  })

  console.log(multipleSelection.value)
}

//删除单门课程
const deleteCourse = async (id: number) => {
  // console.log(id)
  // console.log(toRaw(getCourseData.value))
  // let index = getCourseData.value.findIndex((item: any) => item.id === id)
  // getCourseData.value.splice(index, 1)

  try {
    const confirmResult = await ElMessageBox.confirm(
      '删除课程后将无法恢复，确定继续么？',
      '警告',
      {
        // distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(Delete)
      }
    )

    if (confirmResult === 'confirm') {
      console.log(id)

      const res = await deleteCourseById(id)

      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '课时删除成功！'
        })
        getCourses()
      } else {
        ElMessage({
          type: 'error',
          message: '课时删除失败，或者课程不存在！'
        })
      }
    }
  } catch (error) {
    ElMessage({
      type: 'warning',
      message: '删除已取消！'
    })
  }
}

//批量删除课程

const deleteCourses = async (list: any) => {
  console.log(toRaw(list))

  if (toRaw(list).length === 0) {
    ElMessage.error('未选择要删除的课程！')
    return
  }

  try {
    const confirmResult = await ElMessageBox.confirm(
      '删除课程后将无法恢复，确定继续么？',
      '警告',
      {
        // distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(Delete)
      }
    )

    if (confirmResult === 'confirm') {
      const res: any = await deleteCoursesByIds(toRaw(list))
      console.log(res)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: res.msg
        })
        getCourses()
      } else {
        ElMessage({
          type: 'error',
          message: res.msg
        })
      }
    }
  } catch (error) {
    ElMessage({
      type: 'warning',
      message: '删除已取消！'
    })
  }
}
</script>

<style scoped>
.el-table-column {
  font-weight: bold !important;
}
.el-button {
  color: #fff;
}
.el-icon {
  color: red;
}

:deep(th) {
  font-weight: bolder;
  color: #333;
}
</style>
<!-- <style>
th {
  font-weight: bolder;
  color: #333;
}
</style> -->
